<template>
  <div class="app-container">
    <div>
      <el-button type="primary" plain @click="showJiabanApplyDialog">加班申请</el-button>
    </div>
    <!-- {{list}} -->
    <div style="padding: 10px" />
    <el-table
      v-loading="listLoading"
      :data="list"
      style="width: 100%"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column label="状态" align="center" width="100px">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.sta==0 && scope.row.chexiao==0" type="warning">审核</el-tag>
          <el-tag v-if="scope.row.sta==1 && scope.row.chexiao==0" type="success">通过</el-tag>
          <el-tag v-if="scope.row.sta==2 && scope.row.chexiao==0" type="danger">拒绝</el-tag>
          <el-tag v-if="scope.row.chexiao==1" type="info">撤销</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="申请编号" align="center" width="100px">
        <template slot-scope="scope">
          <el-tag> {{ scope.row.id }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="申请时间" align="center" width="110px">
        <template slot-scope="scope">
          {{ getFormatedTimeStr(scope.row.createTime) }}
        </template>
      </el-table-column>

      <el-table-column label="加班部门" align="center">
        <template slot-scope="scope">
          {{ scope.row.department }}
        </template>
      </el-table-column>

      <el-table-column label="开始时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.startTime }}
        </template>
      </el-table-column>

      <el-table-column label="结束时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.endTime }}
        </template>
      </el-table-column>
      <el-table-column label="时长" align="center">
        <template slot-scope="scope">
          {{ scope.row.shichang }}
        </template>
      </el-table-column>

      <el-table-column label="加班事由" align="center">
        <template slot-scope="scope">
          {{ scope.row.reason }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250px">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" plain @click="seeDetail(scope.row.id)">详情 </el-button>
          <el-button v-if="scope.row.sta>0 && scope.row.chexiao == 0" size="mini" type="primary" plain @click="printPdf(scope.row.id)">生成PDF
          </el-button>
          <el-button v-if="(scope.row.chexiao == 0)" size="mini" type="danger" plain @click="revertApply(scope.$index)">
            撤回 </el-button>
        </template>
      </el-table-column>

    </el-table>

    <div style="padding: 10px" />
    <el-pagination
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageCount"
      layout="total, sizes, prev, pager, next, jumper"
      :total="dataTotal"
      @size-change="onPageSizeChange"
      @current-change="onCurrentPageChange"
    />

    <el-dialog
      :visible.sync="jiabanApplyDialog.visible"
      width="40%"
      :close-on-click-modal="false"
      top="5vh"
      center
      :show-close="false"
    >
      <div>
        <el-form ref="form" size="mini" label-position="left" label-width="100px">
          <el-row>
            <!-- 左侧 -->
            <el-col :span="11">
              <div class="title"><i class="el-icon-document" /> 申请单</div>
              <el-form-item label="部门">
                {{ userInfo.departmentName }}
              </el-form-item>

              <el-form-item label="负责人">
                {{ lingdao.zhijie_lingdao_name}}
              </el-form-item>

              <el-form-item label="加班人">
                {{ userInfo.name }}
              </el-form-item>

              <el-form-item label="开始时间">
                <el-date-picker
                  v-model="jiabanApplyDialog.startTime"
                  type="date"
                  placeholder="选择日期"
                  style="width: 100%;"
                />
                <el-radio-group v-model="jiabanApplyDialog.startWu" size="small" text-color="#fff" fill="#0b847b">
                  <el-radio-button label="1">上午</el-radio-button>
                  <el-radio-button label="2">下午</el-radio-button>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="结束时间">
                <el-date-picker
                  v-model="jiabanApplyDialog.endTime"
                  type="date"
                  placeholder="选择日期"
                  style="width: 100%;"
                />
                <el-radio-group v-model="jiabanApplyDialog.endWu" size="small" text-color="#fff" fill="#0b847b">
                  <el-radio-button label="1">上午</el-radio-button>
                  <el-radio-button label="2">下午</el-radio-button>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="加班时长">
                {{ jiabanTimeStr() }}
              </el-form-item>

              <el-form-item label="加班事由">
                <el-input v-model="jiabanApplyDialog.reason" type="textarea" :rows="4" placeholder="请输入内容" />
              </el-form-item>

              <!-- <el-form-item label="加班人">
                <el-cascader
                  v-model="jiabanApplyDialog.attenders"
                  :options="userList"
                  :props="props"
                  clearable
                  style="width: 100%;"
                />
              </el-form-item> -->

            </el-col>
            <!-- 右侧 -->
            <el-col :span="11" :offset="2">
              <div class="title"><i class="el-icon-s-check" /> 审核流程</div>
              <div v-for="(item,index) in jiabanApplyDialog.auditors" :key="index">
                <!-- 箭头：第一个不显示 -->
                <div v-if="index>0" class="step-arrow">
                  <el-row>
                    <el-col :span="8">
                      <div><i class="el-icon-caret-bottom" /></div>
                    </el-col>
                  </el-row>
                </div>
                <!-- 步骤样式 -->
                <div class="step">
                  <el-row>
                    <el-col :span="8">
                      <div class="step-info-left">{{ item.stepName || item.positionName }}</div>
                    </el-col>
                    <el-col :span="16">
                      <div class="step-info-right">{{ item.name }}</div>
                    </el-col>
                  </el-row>
                </div>
              </div>
            </el-col>
          </el-row>

        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="jiabanApplyDialog.visible = false">关 闭</el-button>
        <el-button type="primary" @click="clickApply()">提 交</el-button>
      </span>
    </el-dialog>
    <el-dialog title="" width="60%" :visible.sync="detailDialog.visible" top="5vh">
      <jiaban-detail :id="detailDialog.id" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="(detailDialog.visible = false)">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  websock
} from '@/websock'
import moment from 'moment'
import {
  quchongAuditors
} from '@/utils/utils'
import JiabanDetail from '../../components/details/jiabanDetail.vue'

export default {
  components: {
    JiabanDetail
  },
  filters: {
    statusFilter(sta) {
      const statusMap = {
        1: 'info',
        2: 'success',
        3: 'danger'
      }
      return statusMap[sta]
    }
  },
  data() {
    return {
      // 人员列表样式(多选)
      props: {
        multiple: true
      },
      // 人员列表数据
      userList: [],
      // 部门列表
      list: null,
      listLoading: true,
      pageIndex: 1,
      pageCount: 10,
      dataTotal: 0,
      userInfo: {},
      lingdao: {}, // 领导
      departmentList: null,
      // 添加员工
      jiabanApplyDialog: {
        visible: false,
        department: '',
        fuzeren: [],
        startTime: '',
        startWu: 0,
        endTime: '',
        endWu: 0,
        reason: '',
        attenders: [],
        auditors: []
      },
      detailDialog: {
        visible: false,
        id: 0
      }
    }
  },
  async created() {
    this.getList()
    websock.getDepartList().then((data) => {
      this.departmentList = data
    })

    const res = await websock.getContactList()
    console.log('created', res)
    const userList = []
    for (let i = 0; i !== res.length; i++) {
      userList.push({
        value: i + '',
        label: res[i].name,
        children: []
      })
      for (let j = 0; j !== res[i].userList.length; j++) {
        userList[i].children.push({
          value: res[i].userList[j].uid,
          label: res[i].userList[j].name
        })
      }
    }
    this.userList = userList

    this.userInfo = await websock.getUserInfo()
    this.lingdao = await websock.getLingdao()

    const auditors = await websock.getAuditors({ typ: 2 })
    console.log('auditors', auditors)
    this.jiabanApplyDialog.auditors = auditors.slice()
    quchongAuditors(this.jiabanApplyDialog.auditors)
  },
  methods: {
    // 获取格式化时间字符串
    getFormatedTimeStr(stamp, str = 'MM-DD HH:mm') {
      return moment(stamp).format(str)
    },
    getList() {
      this.listLoading = true
      websock.jiabanApplyRecordWeb({
        pageIndex: this.pageIndex,
        pageCount: this.pageCount
      }).then(
        (data) => {
          console.log('get list', data)
          this.listLoading = false
          this.list = data.list
          this.dataTotal = data.count
        }
      )
    },
    onPageSizeChange(val) {
      this.pageCount = val
      this.getList()
    },
    onCurrentPageChange(val) {
      this.pageIndex = val
      this.getList()
    },
    // 显示添加员工界面
    showJiabanApplyDialog() {
      this.jiabanApplyDialog.visible = true
      this.jiabanApplyDialog.department = ''
      this.jiabanApplyDialog.fuzeren = []
      this.jiabanApplyDialog.startTime = ''
      this.jiabanApplyDialog.endTime = ''
      this.jiabanApplyDialog.reason = ''
      this.jiabanApplyDialog.attenders = []
    },
    jiabanTimeStr() {
      console.log(this.jiabanApplyDialog)

      if (this.jiabanApplyDialog.startTime == '' || this.jiabanApplyDialog.startWu == 0 || this.jiabanApplyDialog.endTime == '' || this.jiabanApplyDialog.endWu == 0) return ''

      if (moment(this.jiabanApplyDialog.endTime).diff(moment(this.jiabanApplyDialog.startTime), 'day') < 0) return ''

      let startTime = ''
      if (this.jiabanApplyDialog.startWu == 1) {
        startTime = `${moment(this.jiabanApplyDialog.startTime).format('YYYY-MM-DD')} 09:00:00`
      } else if (this.jiabanApplyDialog.startWu == 2) {
        startTime = `${moment(this.jiabanApplyDialog.startTime).format('YYYY-MM-DD')} 13:00:00`
      }

      let endTime = ''
      if (this.jiabanApplyDialog.endWu == 1) {
        endTime = `${moment(this.jiabanApplyDialog.endTime).format('YYYY-MM-DD')} 13:00:00`
      } else if (this.jiabanApplyDialog.endWu == 2) {
        endTime = `${moment(this.jiabanApplyDialog.endTime).format('YYYY-MM-DD')} 17:00:00`
      }

      console.log('jiaban time str', startTime, endTime)

      const diffHours = Math.floor((moment(endTime).valueOf() - moment(startTime).valueOf()) / 1000 / 60 / 60)
      if (diffHours < 0) return ''
      return diffHours + ' 小时'
    },
    async clickApply() {
      console.log('click apply', this.jiabanApplyDialog)

      if (this.jiabanApplyDialog.startTime == 0) {
        return this.$message.error('请选择开始时间')
      }

      if (this.jiabanApplyDialog.endTime == 0) {
        return this.$message.error('请选择结束时间')
      }

      if (this.jiabanApplyDialog.auditors.length == 0) {
        return this.$message.error('请选择审核人员')
      }

      if (moment(this.jiabanApplyDialog.endTime).diff(moment(this.jiabanApplyDialog.startTime)) < 0) return this.$message.error('加班时间错误')

      if (this.jiabanApplyDialog.startTime == this.jiabanApplyDialog.endTime) {
        if (this.jiabanApplyDialog.startWu == 2 && this.jiabanApplyDialog.endWu == 1) return this.$message.error('加班时间错误')
      }

      let startTime = ''
      if (this.jiabanApplyDialog.startWu == 1) {
        startTime = `${moment(this.jiabanApplyDialog.startTime).format('YYYY-MM-DD')} 09:00:00`
      } else if (this.jiabanApplyDialog.startWu == 2) {
        startTime = `${moment(this.jiabanApplyDialog.startTime).format('YYYY-MM-DD')} 13:00:00`
      }

      let endTime = ''
      if (this.jiabanApplyDialog.endWu == 1) {
        endTime = `${moment(this.jiabanApplyDialog.endTime).format('YYYY-MM-DD')} 13:00:00`
      } else if (this.jiabanApplyDialog.endWu == 2) {
        endTime = `${moment(this.jiabanApplyDialog.endTime).format('YYYY-MM-DD')} 17:00:00`
      }

      const auditors = []
      for (let i = 0; i != this.jiabanApplyDialog.auditors.length; i++) {
        auditors.push({
          uid: this.jiabanApplyDialog.auditors[i].uid,
          stepName: this.jiabanApplyDialog.auditors[i].stepName || this.jiabanApplyDialog.auditors[i]
            .positionName
        })
      }

      try {
        await websock.jiabanApply({
          department: this.userInfo.departmentName,
          fuzeren: this.lingdao.zhijie_lingdao,
          startTime,
          startWu: this.jiabanApplyDialog.startWu,
          endTime,
          endWu: this.jiabanApplyDialog.endWu,
          shichang: this.jiabanTimeStr(),
          reason: this.jiabanApplyDialog.reason,
          attenders: [{ uid: this.userInfo.uid, name: this.userInfo.name, avatar: this.userInfo.avatar }],
          auditors
        })

        this.$message.success('提交成功，等待审核')

        this.jiabanApplyDialog.visible = false

        this.getList()
      } catch (err) {
        this.$message.error(err.message || 'error')
      }
    },
    async revertApply(idx) {
      try {
        await websock.revertJiabanApply({
          id: this.list[idx].id
        })
        this.list[idx].sta = 4
		  this.getList()
      } catch (err) {
        console.error(err)
        this.$message.error({
          title: err.message || 'error'
        })
      }
    },
    seeDetail(id) {
      this.detailDialog.visible = true
      this.detailDialog.id = id
    },
    printPdf(id) {
      websock.printPdf({
        typ: 2,
        id
      }).then(res => {
        console.log('print pdf', res)
        const a = document.createElement('a')
        a.style.display = 'none'
        a.href = res
        a.target = '_blank'
        document.body.appendChild(a)
        a.click()
        URL.revokeObjectURL(a.href)
        document.body.removeChild(a)
      })
    }
  }
}
</script>

<style>
  @import url("../../styles/form.css");
</style>
